<?php
require_once($_SERVER['DOCUMENT_ROOT']."/defaultconf.mex");
require_once($GLOBALS['BIB']."Objects/obj.mssql.php");	
$row = 0;
$field = '';
$numb = '';
$fi = '';
$logfile = 'BVA'.$_FILES['file']['name'];
$handle = fopen($_FILES['file']["tmp_name"], "r");

while (($data = fgetcsv($handle, 3000, ",")) !== FALSE) {
    $row++;
	$numb[$row] = $data[0].',';
	$field[$row] = $data[1].','.date("dmY").','.$data[2].',';
	$fieldv[$row] = $data[3].',';
	$Ag = preg_replace( "#[^0-9\-\x\X]#", "",$data[5]);
	$Ag = split('-',$Ag);
	$LAST = count($Ag)-1;
	$fieldv[$row] .= str_pad($Ag[0], 6, "0", STR_PAD_LEFT).',';
	if ($LAST > 0) {
	$fieldv[$row] .= $Ag[$LAST];
	}
	$fieldv[$row] .= ','.str_pad(preg_replace( "#[^0-9\x\X]#", "",$data[6]), 15, "0", STR_PAD_LEFT).',';
	$fieldv[$row] .= str_pad($data[3], 14, "0", STR_PAD_LEFT).','.str_pad($data[7], 18, "0", STR_PAD_LEFT).',';
	$fieldv[$row] .= $data[9];
	
	$cb = $row;
	}

fclose($handle);
$Id = '';
	for ($a = 1; $a <= $cb; $a++) {
		$Id .= $numb[$a];
	}
	$ccj = strlen($Id);
	$Id = substr($Id,0,strlen($Id)-1);

	$dir = 'tmp_files/';
	$saveLocation=$dir . $logfile;
	$handle = fopen($saveLocation,"x");

	LigarMSBSD($BSD['DB01']);
		
		$Names = $GLOBALS['MSCONN']->db_array("SELECT    
			 bpp_IdBanco
		FROM         
			Facturas
		INNER JOIN beneficiarioscuentas ON FraBnfNumero = cb_Id
		INNER JOIN hd_bancospagadores ON bpp_NombreBanco = cb_Banco AND bpp_Corr = 300
		WHERE FraCorresponsal = 300
		AND FraReferenciaCo IN ({$Id})");
		
		for ($b = 1; $b <= $Names[0]; $b++) {
		$fi .= $field[$b].str_pad($Names[$b]['bpp_IdBanco'], 4, "0", STR_PAD_LEFT).$fieldv[$b].PHP_EOL;
		
		}
	fwrite($handle,$fi);
	fclose($handle);
	echo '<a href="'.$saveLocation.'">'.$logfile.'</a>';
?>